import flv from 'flv.js'
const defaultBg = !window.is_official ? require('@/assets/images/default/room-icon-default.jpg') : require('@/assets/images/deticateIp/room-default-over.jpg')
export function customLazyLoad(selector) {
	var lazyloadImages;
	if("IntersectionObserver" in window) {
		lazyloadImages = document.querySelectorAll(selector);
		if(lazyloadImages.length){
			var imageObserver = new IntersectionObserver(function(entries, observer) {
				entries.forEach(function(entry) {
					if(entry.isIntersecting) {
						var image = entry.target;
						image.src = image.dataset.src;
						image.onload = function(){
							this.classList.remove("lazy");
							this.classList.add("img-lazyloaded");
						}
						image.onerror = function(){
							this.onerror = null
							image.src = defaultBg
						}
						imageObserver.unobserve(image);
					}
				});
				if(lazyloadImages.length === 0){
					imageObserver.disconnect();
				}
			});
			[...lazyloadImages].forEach(function(image) {
				imageObserver.observe(image);
			});
		}
	} else {
		var lazyloadThrottleTimeout;
		lazyloadImages = document.querySelectorAll(selector);

		function lazyload() {
			if(lazyloadThrottleTimeout) {
				clearTimeout(lazyloadThrottleTimeout);
			}
			lazyloadThrottleTimeout = setTimeout(function() {
				var scrollTop = window.pageYOffset;
				[...lazyloadImages].forEach(function(img) {
					if((img.getBoundingClientRect().top + scrollTop) < (window.innerHeight + scrollTop)) {
						img.onload = function(){
							this.classList.remove("lazy");
							this.classList.add("img-lazyloaded");
						}
						img.src = img.dataset.src;
						img.onerror = function(){
							this.onerror = null
							img.src = defaultBg
						}
					}
				});
				if(lazyloadImages.length === 0) {
					document.removeEventListener("scroll", lazyload);
					window.removeEventListener("resize", lazyload);
					window.removeEventListener("orientationChange", lazyload);
				}
			}, 20);
		}

		document.addEventListener("scroll", lazyload);
		window.addEventListener("resize", lazyload);
		window.addEventListener("orientationChange", lazyload);
		var event = new Event('scroll');
		document.dispatchEvent(event);
	}
}
export function parseTime(time, cFormat) {
  if (arguments.length === 0) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (('' + time).length === 10) time = parseInt(time) * 1000
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ] }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}
var u = navigator.userAgent, app = navigator.appVersion, ua = navigator.userAgent.toLowerCase();
export	const isMobile = (function(){
  let flag = u.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i)
  return flag
})()
export	let isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);               //ios终端
export	let isWeixin = ua.match(/MicroMessenger/i) == "micromessenger";       //是否微信  
export	let isqq = u.match(/\sQQ/i) == " QQ";
export	let isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1;
export  let isHuwei = navigator.userAgent.toLowerCase().indexOf('huawei') > -1 || navigator.userAgent.toLowerCase().indexOf('honor') > -1
export function iosInputScroll(){
	if(isIOS){
		var wechatInfo = window.navigator.userAgent.match(/MicroMessenger\/([\d\.]+)/i);
		if (!wechatInfo) return;
		var wechatVersion = wechatInfo[1];
		var version = (navigator.appVersion).match(/OS (\d+)_(\d+)_?(\d+)?/);
		if (+wechatVersion.replace(/\./g, '') >= 674 && +version[1] >= 12) {
			window.scrollTo(0,0);
		}
	}
}
export function createNode(htmlStr) {
	var div = document.createElement("div");
	div.innerHTML = htmlStr;
	return div.childNodes[0];
}
export function	stringLen(str){
	return str.replace(/[^\x00-\xff]/g, 'xx').length;
}
export let flvCommon = (function(){
	let flvSupport = (function(){
		let flvSuppot
		if(isHuwei && (!isqq || !isWeixin)){
			flvSuppot = false
		}else{
			flvSuppot = flv.getFeatureList().mseLiveFlvPlayback && !isIOS
		}
		return flvSuppot;
	})()
	let createFlvPlayer = function(url,videoElement){
    let flvPlayer = flv.createPlayer({
      type: 'flv',
      url: url
	},{
        enableWorker: true,
        enableStashBuffer: false,
        stashInitialSize: 128,
		});
    flvPlayer.attachMediaElement(videoElement);
    if(navigator.userAgent.toLowerCase().match(/MicroMessenger/i) == "micromessenger"){
    	flvPlayer.unload();
    	flvPlayer.load();
	    flvPlayer.play().then(function(){
	    	document.querySelector(".fullscreen-video-load").style.display = 'none';	
	    }).catch(function(err){
	    	console.log(err)
	    });
    }
    return flvPlayer;
	}
	let destroyFlvPlayer = function(flvPlayer,flvPlayerPlaying){
		flvPlayer.pause();
    flvPlayer.unload();
		flvPlayer.detachMediaElement();
		flvPlayer.destroy();
	}
	return{
		flvSupport:flvSupport,
		createFlvPlayer:createFlvPlayer,
		destroyFlvPlayer:destroyFlvPlayer,
	}
})()
export function hasClass (el, className) {
  if (el.classList) {
    return Array.prototype.some.call(el.classList, item => item === className)
  } else {
    return !!el.className.match(new RegExp('(\\s|^)' + className + '(\\s|$)'))
  }
}
export function addClass (el, className) {
  if (el.classList) {
    className.replace(/(^\s+|\s+$)/g, '').split(/\s+/g).forEach(item => {
      item && el.classList.add(item)
    })
  } else if (!hasClass(el, className)) {
    el.className += ' ' + className
  }
}
export function removeClass (el, className) {
  if (el.classList) {
    className.split(/\s+/g).forEach(item => {
      el.classList.remove(item)
    })
  } else if (hasClass(el, className)) {
    className.split(/\s+/g).forEach(item => {
      let reg = new RegExp('(\\s|^)' + item + '(\\s|$)')
      el.className = el.className.replace(reg, ' ')
    })
  }
}
export function toggleClass (el, className) {
  className.split(/\s+/g).forEach(item => {
    if (hasClass(el, item)) {
      removeClass(el, item)
    } else {
      addClass(el, item)
    }
  })
}
export function arrayInsert(arr,index, item){
	arr.splice(index, 0, item)
}
export function arrayRemove(arr,from, to){
	var rest = arr.slice((to || from) + 1 || arr.length);
	arr.length = from < 0 ? arr.length + from : from;
	arr.push.apply(arr, rest);
}
export function autoScroll(el){
	el.scrollTop = el.scrollHeight + 1000
}
export function isIphoneX(){
    return /iphone/gi.test(navigator.userAgent) && (screen.height == 812 && screen.width == 375)
}
export function formatWatchServer(watchServer,Base64){
	watchServer.forEach((item)=>{
		if(item.hls && typeof(item.hls) === 'string'){
			item.hls = Base64.decode(item.hls)
		}
		if(item.flv && typeof(item.flv) === 'string'){
			item.flv = Base64.decode(item.flv)
		}
	})
	return watchServer
}
/**
 * 节流函数
 * @param {function} func
 * @param {number} wait 触发时间间隔
 * @param {object} 选项
 */
export	function throttle(func, wait, options = {}) {
  let timeout,
    previous = 0

  return function() {
    let now = +new Date()
    let remain = wait - (now - previous)

    if (remain < 0) {
      if (previous === 0 && !options.begin) {
        previous = now
        return
      }

      if (timeout) {
        clearTimeout(timeout)
        timeout = null
      }

      previous = now
      func.apply(this, arguments)
    } else if (!timeout && options.end) {
      timeout = setTimeout(() => {
        func.apply(this, arguments)
        timeout = null
      }, wait)
    }
  }
}
export function getParents(el,parentClass){
	if(!el){
		return null
	}
	while(el = el.parentNode){
		if(el.classList.contains(parentClass)){
			return el
		}
	}
	return null
}
export function createDom(el = 'div', tpl = '', attrs = {}, cname = '') {
  let dom = document.createElement(el)
  dom.className = cname
  dom.innerHTML = tpl
  Object.keys(attrs).forEach(item => {
    let key = item
    let value = attrs[item]
    if (el === 'video' || el === 'audio') {
      if (value) {
        dom.setAttribute(key, value)
      }
    } else {
      dom.setAttribute(key, value)
    }
  })
  return dom
}
export const ls = {
	set: function (variable, value, expires) {
			const data = {value: value, expires_at: expires}
			localStorage.setItem(variable.toString(), JSON.stringify(data))
	},
	get: function (variable) {
			const data = JSON.parse(localStorage.getItem(variable.toString()))
			if (data !== null) {
					if (data.expires_at !== null && data.expires_at < new Date().getTime()) {
							localStorage.removeItem(variable.toString())
							return null
					} else {
							return data.value
					}
			}
			return null
	}
}